package com.hzya.frame.utils.help;

import com.sun.istack.internal.NotNull;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.cache.WebappTemplateLoader;
import freemarker.ext.dom.NodeModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.servlet.ServletContext;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class FreemarkerHelper {
    private static Configuration CFG = new Configuration()  ;
    private static Log LOG = LogFactory.getLog(FreemarkerHelper.class);
    public static String encode = "utf-8";
    private static boolean loadServletContext = false;

    static {
        try {
            InputStream in = loadFile("freemarker.properties", FreemarkerHelper.class);
            if (in != null) {
                Properties p = new Properties();
                p.load(in);
                CFG.setSettings(p);
            }
        } catch (IOException var5) {
            LOG.error("Error while loading freemarker settings from /freemarker.properties", var5);
        } catch (TemplateException var6) {
            LOG.error("Error while loading freemarker settings from /freemarker.properties", var6);
        }

        if (hasClass("org.sevenstar.web.context.WebContext")) {
            try {
                CFG.setTemplateLoader(new MultiTemplateLoader(new TemplateLoader[]{new WebappTemplateLoader((ServletContext)BeanHelper.invoke(BeanHelper.newInstance("org.sevenstar.web.context.WebContext"), "getServletContext", (Object[])null)), new SevenStarClassTemplateLoader()}));
                loadServletContext = true;
            } catch (Exception var4) {
                CFG.setTemplateLoader(new SevenStarClassTemplateLoader());
            }
        } else {
            CFG.setTemplateLoader(new SevenStarClassTemplateLoader());
    }

        CFG.setObjectWrapper(new SevenStarBeanWrapper());
        CFG.setDefaultEncoding(encode);
        CFG.setOutputEncoding(encode);
        CFG.setNumberFormat("0.####");
        if (hasClass("org.sevenstar.web.cfg.SwebConfigureFactory")) {
            Object obj = null;

            try {
                obj = BeanHelper.invoke(BeanHelper.newInstance("org.sevenstar.web.cfg.SwebConfigureFactory"), "getSwebModel", (Object[])null);
            } catch (Throwable var3) {
                ;
            }

            if (obj != null) {
                try {
                    encode = (String)BeanHelper.getPropertyValue("encode", obj);
                } catch (Throwable var2) {
                    ;
                }
            }
        }

        if (encode == null || "".equals(encode)) {
            encode = "utf-8";
        }

    }

    private FreemarkerHelper() {
    }

    private static boolean hasClass(String className) {
        try {
            Class.forName(className);
            return true;
        } catch (Throwable var2) {
            return false;
        }
    }

    public static void main(String[] args) {

        getNodeModelFromXml(null);
        //System.out.println(process("com/ctzj/eprm/inf/prm/cabasi/template/CTZJ_SIQuery_Full_SI.xml", "serialNum", (Object)"18924980793"));
    }
    public static NodeModel getNodeModelFromXml(String xml) {
        try {
            if(xml == null){
                throw new RuntimeException(" 文件不能为空！");
            }
            if ( xml.indexOf("xmlns:xsi") != -1) {
                xml = xml.replaceFirst("xmlns:xsi", "pmlns");
            }

            if (xml.indexOf("xmlns") != -1) {
                xml = xml.replaceFirst("xmlns", "pmlns");
            }

            return NodeModel.parse(new InputSource(new StringReader(xml)));
        } catch (SAXException var2) {
            throw new RuntimeException("xml格式错误");
        } catch (IOException var3) {
            throw new RuntimeException("没有输入值");
        } catch (ParserConfigurationException var4) {
            throw new RuntimeException("xml格式错误");
        }catch (Exception e){
            throw new RuntimeException("未知异常");
        }

    }

    public static String process(String templatePath, String key, Object value) {
        Map<String, Object> root = new HashMap<String, Object>();
        root.put(key, value);
        return process(templatePath, root);
    }

    public static String process(String key, String content, Map<?, ?> root) {
        ServletContext sc = null;
        if (hasClass("org.sevenstar.web.context.WebContext")) {
            sc = (ServletContext)BeanHelper.invoke(BeanHelper.newInstance("org.sevenstar.web.context.WebContext"), "getServletContext", (Object[])null);
        }

        if (sc != null && !loadServletContext) {
            try {
                CFG.setTemplateLoader(new MultiTemplateLoader(new TemplateLoader[]{new WebappTemplateLoader(sc), new SevenStarClassTemplateLoader()}));
                loadServletContext = true;
            } catch (Throwable var14) {
                ;
            }
        }

        try {
            Template template = new Template(key, new StringReader(content), CFG);
            StringWriter writer = new StringWriter();

            try {
                template.process(root, writer);
                writer.flush();
            } finally {
                writer.close();
            }

            return writer.toString();
        } catch (IOException var12) {
            throw new RuntimeException(var12);
        } catch (TemplateException var13) {
            throw new RuntimeException(var13);
        }
    }

    public static String process(String templatePath, Map<String, Object> root) {
        Template template = null;
        ServletContext sc = null;
        if (hasClass("org.sevenstar.web.context.WebContext")) {
            sc = (ServletContext)BeanHelper.invoke(BeanHelper.newInstance("org.sevenstar.web.context.WebContext"), "getServletContext", (Object[])null);
        }

        if (sc != null && !loadServletContext) {
            try {
                CFG.setTemplateLoader(new MultiTemplateLoader(new TemplateLoader[]{new WebappTemplateLoader(sc), new SevenStarClassTemplateLoader()}));
                loadServletContext = true;
            } catch (Throwable var13) {
                ;
            }
        }

        try {
            template = CFG.getTemplate(templatePath);
            template.setEncoding(encode);
            StringWriter writer = new StringWriter();

            try {
                template.process(root, writer);
                writer.flush();
            } finally {
                writer.close();
            }

            return writer.toString();
        } catch (IOException var11) {
            throw new RuntimeException(var11);
        } catch (TemplateException var12) {
            throw new RuntimeException(var12);
        }
    }



    private static InputStream loadFile(String fileName, Class<FreemarkerHelper> clazz) {
        new SevenStarClassTemplateLoader();
		URL fileUrl =  SevenStarClassTemplateLoader.getResource(fileName, clazz);
        if (fileUrl == null) {
            return null;
        } else {
            try {
                InputStream is = fileUrl.openStream();
                if (is == null) {
                    throw new IllegalArgumentException("No file '" + fileName + "' found as a resource");
                } else {
                    return is;
                }
            } catch (IOException var5) {
                throw new IllegalArgumentException("No file '" + fileName + "' found as a resource");
            }
        }
    }

}
